package com.power.sifa.util;

import cn.hutool.core.util.RandomUtil;
import com.plf.common.utils.SpringHolder;
import com.power.sifa.approve.dao.Apl_arrive_receiptDao;
import com.power.sifa.approve.model.Apl_arrive_receipt;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

public class VerifyCodeUtil {

    // 定义字符集
    private static final String CHARACTERS = "23456789abcdefghijklmnpqrstuvwxyz";

    private static final Random RANDOM = new Random();

    /**
     * 生成随机位数的验证码
     *
     * @param length 长度
     * @return 验证码
     */
    public static String generateCode(Integer length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length());
            char randomChar = CHARACTERS.charAt(index);
            sb.append(randomChar);
        }
        return sb.toString();
    }

    /**
     * 查询不重复的数字验证码
     *
     * @return
     */
    public static String getVerify() {
        Apl_arrive_receiptDao apl_arrive_receiptDao = SpringHolder.getBean(Apl_arrive_receiptDao.class);
        // 验证码调整为数字验证码
        String code = RandomUtil.randomNumbers(6);
        Apl_arrive_receipt receiptObj = apl_arrive_receiptDao.getByVerifycode(code);
        if (null == receiptObj) {
            return code;
        } else {
            return getVerify();
        }
    }
}
